<!-- home -->
<template>
  <div class="container">
    <van-cell-group inset>
      <van-field v-model="inviter" type="digit" :maxlength="4" center label="邀请码" placeholder="请输入4位数邀请码">
        <template #button>
          <van-button size="small" type="primary" @click="upload" :disabled="!canUpload">{{
            isInviter ? '已验证' : '提交'
          }}</van-button>
        </template>
      </van-field>
    </van-cell-group>
  </div>
</template>

<script>
// 请求接口
import { uploadInviter } from '@/api/user.js'
import { Toast, Dialog } from 'vant'
export default {
  data() {
    return {
      // 邀请码是否认证通过
      isInviter: false,
      inviter: ''
    }
  },
  computed: {
    canUpload() {
      return this.inviter.length == 4 && !this.isInviter
    }
  },
  mounted() {
    const inviter = this.$store.getters.userInfo.inviter
    if (inviter) {
      this.isInviter = true
      this.inviter = inviter
    }
  },
  methods: {
    async upload() {
      let toast = Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        loadingType: 'spinner',
        message: '正在提交'
      })
      try {
        const { msg } = await uploadInviter({ inviter: this.inviter })
        Dialog.alert({
          message: msg
        })
        // 更新全局store数据 && 更新邀请码
        this.$store.dispatch('setUserBaseInfo')
      } finally {
        toast.clear()
      }
    }
  }
}
</script>
<style lang="scss">
.container {
  margin: 10px 0;
}
</style>
